package com.intelligent.ispc.common.persistence.jdbc;

import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * Created by Peter on 15/11/25.
 */
public class JdbcSeachFilter {

    public enum Operator {
        EQ, LIKE, GT, LT, GTE, LTE
    }

    public String fieldName;
    public Object value;
    public Operator operator;

    public JdbcSeachFilter(String fieldName, Operator operator, Object value) {
        this.fieldName = fieldName;
        this.value = value;
        this.operator = operator;
    }

    /**
     * The key format in searchParams: OPERATOR_FIELDNAME
     */
    public static Map<String, JdbcSeachFilter> parse(Map<String, Object> searchParams) {
        Map filters = Maps.newHashMap();
        for (Map.Entry entry : searchParams.entrySet()) {

            String key = (String) entry.getKey();
            Object value = entry.getValue();
            if (StringUtils.isBlank((String) value)) {
                continue;
            }

            // split operator and filedAttribute
            String[] names = StringUtils.split(key, "_");
            if (names.length != 2) {
                throw new IllegalArgumentException(key + " is not a valid search filter name");
            }
            String filedName = names[1];
            Operator operator = Operator.valueOf(names[0]);

            // Create the searchFilter
            JdbcSeachFilter filter = new JdbcSeachFilter(filedName, operator, value);
            filters.put(key, filter);
        }

        return filters;
    }
}
